<template>
  <!--  查询 -->
  <div>
    <el-input placeholder="请输入客户姓名" style="width:200px" v-model="queryName"></el-input>
    <el-button @click="queryByName" type="success" plain>查询</el-button>
    <el-button @click="showCustomerDialog" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px">
      登&emsp;记
    </el-button>
  </div>
  <!--  显示所有客户信息 table自动循环-->
  <div>{{errorMessage}}</div>
  <el-table :data="customerList">
    <el-table-column label="序号" type="index" width="60px"></el-table-column>
    <el-table-column prop="customerName" label="客户姓名" width="80px"></el-table-column>
    <el-table-column prop="customerSex" label="性别" width="60px">
      <template #default="scope">
        {{scope.row.customerSex === 0?'男':'女'}}
      </template>
    </el-table-column>
    <el-table-column prop="customerAge" label="年龄" width="60px"></el-table-column>
    <el-table-column prop="idcard" label="身份证号" width="150px"></el-table-column>
    <el-table-column prop="buildingNo" label="所属楼房" width="80px"></el-table-column>
    <el-table-column prop="roomNo" label="房间号" width="80px"></el-table-column>
    <el-table-column prop="bedNo" label="床号" width="80px"></el-table-column>
    <el-table-column prop="checkinDate" label="入住日期" width="110px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="expirationDate" label="合同到期时间" width="110px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="contactTel" label="联系电话" width="120px"></el-table-column>
    <el-table-column prop="familyMember" label="家属" width="80px"></el-table-column>

    <el-table-column  label="操作" width="200px">
      <template #default="scope">
<!--        <div>{{scope.row}}</div>-->
        <el-button v-if="!scope.row.isDeleted"  type="primary" @click="showEditDialog(scope.row.id)">修改</el-button>
        <el-button v-if="!scope.row.isDeleted"  type="primary" @click="showEditDialog(scope.row.id)">分配床位</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
    />
  </div>

  <!--  客户信息对话框 -->
  <el-dialog v-model="customerDialog" :title="dialogTitle">
    <el-form :model="curCustomer">
      <el-form-item label="客户姓名">
        <el-col :span="11">
          <el-input v-model="curCustomer.customerName"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="性&emsp;&emsp;别">
        <el-col :span="11">
          <el-select v-model="curCustomer.customerSex">
            <el-option
                v-for="item in sexOptions"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>

      <el-form-item label="身份证">
        <el-col :span="11">
          <el-input v-model="curCustomer.idcard"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="年&emsp;&emsp;龄">
        <el-col :span="11">
          <el-input v-model="curCustomer.customerAge"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="家&emsp;&emsp;属">
        <el-col :span="11">
          <el-input v-model="curCustomer.familyMember"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="电&emsp;&emsp;话">
        <el-col :span="11">
          <el-input v-model="curCustomer.contactTel"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="入住日期">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.checkinDate"></el-date-picker>
        </el-col>
      </el-form-item>

      <el-form-item label="合同到期时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.expirationDate"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="所属楼房">
        <el-col :span="11">
          <el-select v-model="curBuilding" placeholder="（选所属楼房）">
            <el-option
                v-for="building in buildingOptions"

                :key="building.id"
                :label="building.buildingNo"
                :value="building.buildingNo"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="房间编号">
        <el-col :span="11">
          <el-select v-model="curRoom" placeholder="（选房间编号）">
            <el-option
                v-for="room in roomOptions"

                :key="room.id"
                :label="room.roomNo"
                :value="room.roomNo"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="床位号">
        <el-col :span="11">
          <el-select v-model="curCustomer.bedNo" >
            <el-option
                v-for="bed in bedOptions"

                :key="bed.id"
                :label="bed.bedNo"
                :value="bed.bedNo"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>

    </el-form>
    <el-button @click="optOne()">{{buttonOpt}}</el-button>
  </el-dialog>
</template>


<script setup>
import {ref, onMounted, reactive, watch} from "vue";
import http from '@/axios/http';
import qs from "qs";
// 存放用户数据集合
let customerList = ref([]);

//报错提示
let errorMessage = ref("")

//模糊查询绑定的 客户名称
let queryName = ref("")

//对话框显示控制
let customerDialog = ref(false)

//客户信息，或者编辑已有客户的 绑定数据
let curCustomer = ref({
  roomNo: {
    roomNo: ""
  },  buildingNo: {
    buildingNo: ""
  }
});

//登记、修改客户信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = reactive("")
let buttonOpt = reactive("")

//对话框操作类型：1：添加 2：编辑
let dialogOptType = reactive(1)
let size = 10; //当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; //每页显示行数

//当前页码信息
let pageContains = ref({})

//性别数组（其他字典值查询出来也是同样数据结构，使用方法类似）
let sexOptions = ref([
  {
    label: '男',
    value: 0
  },{
    label: '女',
    value: 1
  }
])

//绑定下拉框数据
let roomOptions = ref({});
let buildingOptions = ref({});
let bedOptions = ref({});

//获取下拉框关联的数据
function getbuildingData(){
  //获取下拉框的数据
  http.post('/lyy/beds/get_all_building').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerOptions
        if(result.result === 'success'){
          buildingOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )

}
//获取下拉框关联的数据
function getroomData(){
  //获取下拉框的数据
  http.post('/lyy/beds/get_all_room').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerOptions
        if(result.result === 'success'){
          roomOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )

}
//获取下拉框关联的数据
function getbedData(){
  //获取下拉框的数据
  http.post('/lyy/beds/get_all_bed').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerOptions
        if(result.result === 'success'){
          bedOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )

}

//记录当前选中的护理内容的等级名称
let curBuilding = ref("");

// 监听护理等级变化
watch(curBuilding, (newBuilding) => {
  //根据等级筛选护理内容
  if (newBuilding) {

    curCustomer.value.buildingNo=newBuilding;
    //传递的参数形式，必须为这种形式
    let param = {
      buildingNo : newBuilding
    }
    //根据护理等级改变护理内容选项
    http.post('/lyy/beds/getroom_by_building',qs.stringify(param)).then(
        (res)=>{
          let result = res.data;
          // 返回结果传给 nursingOptions
          if(result.result === 'success'){
            roomOptions.value = result.data;
          } else {
            errorMessage.value = result.error;
          }
        }
    )

  }
});

let curRoom = ref("");

// 监听护理等级变化
watch(curRoom, (newRoom) => {
  curCustomer.value.roomNo=newRoom;
  if (newRoom && curBuilding.value) {
    let params = {
      buildingNo: curBuilding.value,
      roomNo: newRoom
    };
    http.post('/lyy/beds/getbed_by_buildingroom', qs.stringify(params)).then(
        (res) => {
          let result = res.data;
          if(result.result === 'success'){
            bedOptions.value = result.data;
          } else {
            errorMessage.value = result.error;
          }
        }
    )
  }
});

//根据客户姓名模糊查询客户信息
function queryByName(){

  let param = {
    customerName: queryName.value
  }

  http.post('/lyy/get_customers_by', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerList
        if(result.result === 'success'){
          customerList.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//单击登录按钮事件
function showCustomerDialog(){
  curCustomer.value={};
  getbuildingData();
  getroomData();
  getbedData();
  dialogTitle = "客户入住登记";
  buttonOpt="录入"
  //弹出客户信息对话框
  customerDialog.value = true;
  dialogOptType = 1 //设置当前操作类型标志是 录入
  curBuilding.value = "";
  curRoom.value="";
}

//关闭客户信息对话框
function closeCustomerDialog(){
  customerDialog.value = false;
}

//页面初始化
onMounted(
    ()=>{
      init();
    }
)

function init(){
  //查询所有用户信息
  getAllCustomers();
  //查询需要的字典（{标志1: 值1, 标志2: 值2}）
  //用的时候取 字典[字段值（字典标志）]
}


function getAllCustomers(){
  let params = ref({
    size: size,
    pageNum: pageNum,
    pageSize: pageSize
  })

  http.post('/lyy/get_all_customers_bed', params.value).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerList
        if(result.result === 'success'){
          pageContains.value = result.data;
          //pageContains.list = null;
          customerList.value = result.data.list;

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//格式化日期
function formatDate(row, column){
  let data = row[column.property];

  if(data == null){
    return null;
  }

  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
  //+ ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
}

function recordOne(){
  let param = curCustomer.value;
  http.post('/lyy/add_one_customer', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerList
        if(result.result === 'success'){
          //关闭对话框
          closeCustomerDialog()

          // // 存储新添加的客户ID
          // let newCustomerId = result.customerId;
          //
          // // 弹出床位分配对话框
          // openBedDialog(newCustomerId);

          //刷新客户列表
          getAllCustomers();
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}


// //显示床位分配对话框
// function openBedDialog(newCustomerId){
//
// }

//显示编辑对话框
function showEditDialog(customerid){
  //根据id查询客户信息
  getCustomerInfo(customerid);
  getbuildingData();
  getroomData();
  getbedData();



  //显示对话框
  console.log(customerid)
  customerDialog.value = true;
  dialogTitle = "客户入住信息修改";
  buttonOpt="修改"

  dialogOptType = 2 //设置当前操作类型标志是 修改

  curBuilding.value = "";
  curRoom.value="";

}

function getCustomerInfo(customerid){
  let param = {
    customerid : customerid
  }
  http.post('/lyy/getcustomerby_id', qs.stringify(param)).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerList
        if(result.result === 'success'){
          curCustomer.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function editOne(){
  let param = curCustomer.value;
  http.post('/lyy/modifycustomerby_id', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          //curCustomer.value = result.data;
          closeCustomerDialog();
          getAllCustomers();

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function editStatus(){
  let param = curCustomer.value;
  http.post('/lyy/update_status', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          //curCustomer.value = result.data;
          closeCustomerDialog();
          getAllCustomers();

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function optOne(){
  if(dialogOptType === 1){
    recordOne()
    editStatus()
  } else if(dialogOptType === 2) {
    editOne()
    editStatus()
  }
}

//分页处理
const handlePageChange = (pageNum1)=>{
  pageNum = pageNum1
  getAllCustomers()
}

const handleSizeChange = (pageSize1)=>{
  pageSize = pageSize1
  getAllCustomers()
}
</script>

<style scoped>

</style>